//#pragma once

#ifndef __STRING_H__
#define __STRING_H__

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
using namespace std;

#include <cassert>

namespace yyp
{
	class string
	{
	public:
		friend void swap(string& s1, string& s2);
		friend ostream& operator<<(ostream& out, const string& str);
		friend istream& operator>>(istream& in, string& str);

	public:
		typedef char* iterator;
		typedef const char* const_iterator;

	public:
		string(const char* s = "");
		string(const string& str);
		~string()
		{
			if (_str)
			{
				delete[] _str;
				_str = nullptr;
				_size = _capacity = 0;
			}
		}

		///////////////////////// iterator
		iterator begin()
		{
			return _str;
		}

		iterator end()
		{
			return _str + _size;
		}

		const_iterator begin() const
		{
			return _str;
		}

		const_iterator end() const
		{
			return _str + _size;
		}

		///////////////////////// modify
		void push_back(char c);
		string& operator+=(char c);
		string& operator+=(const string& str);
		string& append(const string& str);
		void clear()
		{
			_size = 0;
			_str[_size] = '\0';
		}

		void swap(string& str)
		{
			std::swap(_str, str._str);
			std::swap(_size, str._size);
			std::swap(_capacity, str._capacity);
		}

		string& operator=(const string& str);

		const char* c_str() const
		{
			return _str;
		}

		///////////////////////// capacity
		void reserve(size_t n = 0);
		void resize(size_t n, char c = '\0');
		bool empty() const
		{
			return _size == 0;
		}

		size_t size() const
		{
			return _size;
		}

		size_t capacity() const
		{
			return _capacity;
		}

		///////////////////////// access
		char& operator[](size_t pos)
		{
			assert(pos < _size);

			return _str[pos];
		}

		const char& operator[](size_t pos) const
		{
			assert(pos < _size);

			return _str[pos];
		}

		///////////////////////// relational operators
		bool operator<(const string& str) const;
		bool operator<=(const string& str) const;
		bool operator>(const string& str) const;
		bool operator>=(const string& str) const;
		bool operator==(const string& str) const;
		bool operator!=(const string& str) const;

		///////////////////////// others
		size_t find(char c, size_t pos = 0) const;
		size_t find(const string& str, size_t pos = 0) const;

		string& insert(size_t pos, size_t n, char c);
		string& insert(size_t pos, const string& str);

		string& erase(size_t pos = 0, size_t len = npos);

		string substr(size_t pos = 0, size_t len = npos);

	public:
		static const size_t npos;

	private:
		//char _buff[16];
		char* _str = nullptr;

		size_t _size = 0;
		size_t _capacity = 0;
	};

	void swap(string& s1, string& s2);

	ostream& operator<<(ostream& out, const string& str);
	istream& operator>>(istream& in, string& str);
}

#endif

